package com.vcms.utility.loader.storage.engine.file;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import com.vcms.exception.VMCSException;
import com.vcms.utility.loader.storage.engine.StorageEngine;

/**
 * @author robin.foe A0092657U
 * Bridge design pattern refined implementor, for FILE/PROPERTIES related parser
 */
public abstract class FileStorageEngine<T> extends StorageEngine<T>{
	
	private Properties properties;
	private String fileName;
	
	public FileStorageEngine(String fileName) throws VMCSException{
		this.fileName = fileName;
		this.initialize();
	}
	
	private void initialize() throws VMCSException{
		try {
			properties = new Properties(System.getProperties());
			FileInputStream stream = new FileInputStream(fileName);
			properties.load(stream);
			stream.close();
		} catch (Exception e) {
			throw new VMCSException("FileStorageEngine.initialize","Error loading STORE properties: " + e);
		}
	}
	
	@Override
	public int getItemCount(){return Integer.parseInt(properties.getProperty("NumOfItems"));}
	
	@Override
	public void setItemCount(int count){properties.setProperty("NumOfItems", String.valueOf(count));}
	
	@Override
	public void flush()throws VMCSException{
		try {
			FileOutputStream os = new FileOutputStream(fileName);
			properties.store(os, "-----------fileName----------");
			os.close();
		} catch (IOException e) {
			throw new VMCSException("FileStorageEngine.flush",	"Error in saving the property file" + e);
		}
	}
	
	/**helper function**************************************************/
	protected String getValueFromProperty(String key){return properties.getProperty(key);}
	protected void setValueToProperty(String key, String value){properties.setProperty(key, value);}
	
}
